package com.qiankan.qmsj.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.qiankan.qmsj.R;
import com.qiankan.qmsj.adapter.CommonAdapter;
import com.qiankan.qmsj.entity.Labels;
import com.qiankan.qmsj.entity.Product;
import com.qiankan.qmsj.entity.ProductClassifyEntity;
import com.qiankan.qmsj.entity.Result;
import com.qiankan.qmsj.net.APIHub;
import com.qiankan.qmsj.utils.AsyncLoadImage;
import com.qiankan.qmsj.utils.ColorUtils;
import com.qiankan.qmsj.utils.StringUtils;
import com.qiankan.qmsj.viewHolder.ClassifyViewHolder;
import com.qiankan.qmsj.viewHolder.CommonViewHolder;
import com.qiankan.qmsj.widget.TipToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProductByTypeActivity extends BaseActivity {
    @BindView(R.id.emptyView)
    LinearLayout mEmptyView;
    @BindView(R.id.tv_title)
    TextView mTitle;
    @BindView(R.id.iv_product)
    ImageView imgBanner;
    @BindView(R.id.rv_product)
    RecyclerView mRvProduct;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private String type = "";//类型
    private String minMoney = "";//最小金额
    private String maxMoney = "";//最大金额
    private String minTime = "";//时间
    private String order = "";//排序
    private List<Product> productList;
    private CommonAdapter<Product> productListAdapter;

    @Override
    public int getContentViewId() {
        return R.layout.activity_product_by_type;
    }

    public static Intent newIntent(Context context, Bundle bundle) {
        Intent intent = new Intent(context, ProductByTypeActivity.class);
        intent.putExtras(bundle);
        return intent;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type");

        minTime = TextUtils.isEmpty(bundle.getString("minTime")) ? "" : bundle.getString("minTime");
        minMoney = TextUtils.isEmpty(bundle.getString("minMoney")) ? "" : bundle.getString("minMoney");
        maxMoney = TextUtils.isEmpty(bundle.getString("maxMoney")) ? "" : bundle.getString("maxMoney");
        order = TextUtils.isEmpty(bundle.getString("order")) ? "" : bundle.getString("order");

        mTitle.setText(bundle.getString("title"));
        if (bundle.getBoolean("isShowBanner")) {
            imgBanner.setVisibility(View.VISIBLE);
            AsyncLoadImage.loadImage(bundle.getString("banner"), imgBanner);
        } else {
            imgBanner.setVisibility(View.GONE);
        }
        mRvProduct.setHasFixedSize(true);
        mRvProduct.setLayoutManager(new LinearLayoutManager(this));
        mRvProduct.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        productList = new ArrayList<>();
        productListAdapter = new CommonAdapter<Product>(this, ClassifyViewHolder.class, productList, R.layout.classify_item) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, final Product item, int position) {
                ClassifyViewHolder viewHolder = (ClassifyViewHolder) holder;
                viewHolder.mProductName.setText(item.getName());
                viewHolder.mProductTitle.setText(item.getName());
                viewHolder.mProduceIntro.setText(item.getIntro());
                if (!TextUtils.isEmpty(item.getGrade())) {
                    viewHolder.mProductStars.setRating(Float.parseFloat(item.getGrade()));
                }
                AsyncLoadImage.loadImage(item.getIcon(), viewHolder.mProductLogo, R.mipmap.ic_launcher);
                StringUtils.setTVColor("最高金额：" + StringUtils.convertNum(item.getMaxmoney()) + "元 ", '：', '元', getResources().getColor(R.color.dark_yellow), viewHolder.mMaxMoney);
                StringUtils.setTVColor("成功贷款：" + StringUtils.convertNum(item.getApplynum()) + "人 ", '：', '人', getResources().getColor(R.color.black_text), viewHolder.mApplyNum);
                viewHolder.mLabelRoot.removeAllViews();
                for (Labels label : item.getLabels()) {
                    TextView textView = new TextView(ProductByTypeActivity.this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(10, 0, 0, 0);
                    textView.setPadding(5, 1, 5, 1);
                    textView.setTextSize(12);
                    textView.setLayoutParams(lp);
                    textView.setText(label.getName());
                    textView.setTextColor(Color.parseColor("#FFFFFF"));
                    try {
                        textView.setBackgroundColor(Color.parseColor(ColorUtils.getHex(label.getColor())));
                    } catch (Exception e) {

                    }
                    viewHolder.mLabelRoot.addView(textView);
                }
                viewHolder.setOnRecyclerViewListener(new CommonViewHolder.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(View view) {
                        Intent intent = ProductDetailActivity.newIntent(ProductByTypeActivity.this, item);
                        startActivity(intent);
                    }
                });
            }
        };
        mRvProduct.setAdapter(productListAdapter);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh();
            }
        });
        refresh();
    }

    private void refresh() {
        Map<String, String> param = new HashMap<String, String>();
        if (!TextUtils.isEmpty(type)) {
            param.put("type", type);
        }
        if (!TextUtils.isEmpty(minMoney)) {
            param.put("minmoney", minMoney);
        }
        if (!TextUtils.isEmpty(maxMoney)) {
            param.put("maxmoney", maxMoney);
        }
        if (!TextUtils.isEmpty(minTime)) {
            param.put("mintime", minTime);
        }
        if (!TextUtils.isEmpty(order)) {
            param.put("order", order);
        }
        showLoadingDialog();
        if (param.size() > 0) {
            APIHub.getsInstance().getBaseService().getProductForType(param).enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    smartRefreshLayout.finishRefresh();
                    dismissLoadingDialog();
                    Result result = response.body();
                    if (result.getCode().equals("200")) {
                        productList.clear();
                        ProductClassifyEntity productClassifyEntity = new Gson().fromJson(result.getData(), ProductClassifyEntity.class);
                        productList.addAll(productClassifyEntity.getProducts());
                        if (productList.size() == 0) {
                            mEmptyView.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyView.setVisibility(View.GONE);
                        }
                        productListAdapter.notifyDataSetChanged();
                    } else {
                        TipToast.toast(ProductByTypeActivity.this, result.getRemark());
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    smartRefreshLayout.finishRefresh();
                    dismissLoadingDialog();
                    TipToast.toast(ProductByTypeActivity.this, "网络连接失败");
                }
            });
        } else {
            APIHub.getsInstance().getBaseService().getProductForType().enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    smartRefreshLayout.finishRefresh();
                    dismissLoadingDialog();
                    Result result = response.body();
                    if (result.getCode().equals("200")) {
                        productList.clear();
                        ProductClassifyEntity productClassifyEntity = new Gson().fromJson(result.getData(), ProductClassifyEntity.class);
                        productList.addAll(productClassifyEntity.getProducts());
                        productListAdapter.notifyDataSetChanged();
                    } else {
                        TipToast.toast(ProductByTypeActivity.this, result.getRemark());
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    smartRefreshLayout.finishRefresh();
                    dismissLoadingDialog();
                    TipToast.toast(ProductByTypeActivity.this, "网络连接失败");
                }
            });
        }
    }

    @OnClick(R.id.iv_back)
    public void onClickBack(View view) {
        finish();
    }
}
